(function(factory) {
	if (typeof define === "function" && define.amd) {
		define(["jquery"], function(jQuery) {
			factory(jQuery);
		})
	} else if (typeof define === "function" && define.cmd) {
		define(function(require, exports, module) {
			require.async("jquery", factory(JQuery));
		});
	} else {
		factory(window.jQuery);
	}
})(function($) {
	if (!$) {
		error("需要jQuery");
	}
	var
		options = {
			height: "300px",
			toolbar: ["bold", ["styles"]]
		},

		/**
		 * 一个编辑器对象所包含的方法和属性
		 * @type {Object}
		 */
		coreEditor = {
			html: function(content) {
				if (content) {
					this.$edit.html(content);
					return this;
				} else {
					return this.$edit.html();
				}
			}
		},
		/**
		 * 事件处理
		 * @type {Object}
		 */
		Events = {
			inputHandle: function(event) {
				coreEditor.pos = document.getSelection();

			}
		},
		agent = {
			isMSIE: navigator.userAgent.indexOf('MSIE') > -1 || navigator.userAgent.indexOf('Trident') > -1,
			isIE8: this.isMSIE && (/MSIE\s*(?=5.0|6.0|7.0|8.0)/i).test(window.navigator.appVersion)
		},
		/**
		 * DOM操作的一些方法
		 * @type {Object}
		 */
		dom = {
			hasAttr: function(el, name) {
				var attr = el.getAttributeNode && el.getAttributeNode(name);
				return attr ? attr.specified : false
			}
		},
		plugins = {
			"bold": {
				init: function() {
					console.log("bold init");
					return Button({
						icon: "bold"
					})
				}
			},
			"styles": {
				init: function() {
					console.log("styles init");

					return Button({
						btnText: "dropdown",
						dropdown: ["1", "2"]
					}, "dropdown");
				}
			}
		};
	var Button = function(opts, type) {
		var config = {
			type: "", //定义是按钮还是下拉
			btnType: "", //定义按钮的情景模式
			btnClass: "", //定义按钮额外样式
			icon: "", //按钮的图标
			btnText: "", //按钮的文字
			eventValue: "", //事件触发传入的值
			eventHandler: "", //click事件处理
			dropdown: "", //下拉列表array存string/object {eventValue,eventHandler,value}
		};
		if (opts.type) {
			type = opts.type;
		}
		if (type === "group") {
			return $("<div class='btn-group btn-group-sm'>");
		} else {
			var btn = $("<buton type='button' class='btn btn-sm btn-small'>");
			opts.btnType = opts.btnType ? "btn-" + opts.btnType : null;
			btn.addClass(opts.btnType || "btn-default");
			btn.addClass(opts.class || "");
			btn.append($("<i class='fa fa-" + opts.icon || "" + "'></i>"));
			btn.append(opts.btnText || "");
			for (var attr in opts) {
				if (/^data/.test(attr)) {
					btn.attr(attr, opts[attr]);
				}
			}
		}
		if (type === "dropdown") {
			var group = Button({}, "group");
			var dropdown = Button({
				class: "dropdown-toggle",
				"data-toggle": "dropdown"
			});
			var ul = $("<ul class='dropdown-menu' role='menu'>");
			dropdown.html(btn.html() + "<span class='caret'></span>");
			$.each(opts.dropdown, function(i, n) {
				if (typeof n === "object") {
					ul.append($("<li><a href='#' data-value='" + n.eventValue || n.value + "' data-event='" + n.eventHandler + "'>" + n.value + "</a></li>"))
				} else {
					ul.append($("<li><a href='#' data-value='" + opts.eventValue || n + "' data-event='" + opts.eventHandler + "'>" + n + "</a></li>"))
				}

			});
			group.append(dropdown);
			group.append(ul);
			return group;
		}
		return btn;
	};
	/**
	 * 加载css
	 * @return {[type]}
	 */
	;
	(function loadCss() {
		var path = document.scripts[document.scripts.length - 1].src.slice(0, document.scripts[document.scripts.length - 1].src.lastIndexOf("/") + 1);
		$("<link>").attr({
			"href": path + "xyzEditor.css",
			"type": "text/css",
			"rel": "stylesheet"
		}).appendTo($("head"));
	})()

	function error(err) {
			throw new Error(err);
		}
		/**
		 * 构建编辑器骨架
		 * @param  {[type]}
		 * @return {[type]}
		 */
	function initBone($target) {
		coreEditor.$toolbar = $toolbar = $("<div class='xyzEditor_toolbar'>");
		$toolbar.append($("<div class='btn-toolbar' role='toolbar'>"));
		coreEditor.$body = $body = $("<div class='xyzEditor_body'>");
		coreEditor.$edit = $edit = $("<div class='xyzEditor_edit' contenteditable='true' style='height:" + options.height + "'>");
		coreEditor.$source = $target;
		$target.hide();
		$target.before($toolbar);
		$target = $target.detach();
		$body.append($edit).append($target);
		$toolbar.after($body);
		//绑定事件
		$edit.on("input", Events.inputHandle);
		//非表单元素在设置tableIndx属性后才会响应focus/blur事件
		//$body.attr("tableIndex","-1");
		//$edit.on("click keyup", Events.focusHandle);
	}

	function createToolbar(edit) {
		var toolbar = coreEditor.$toolbar.find("div[class=btn-toolbar]"),
			btnGroup;
		//toolbar.append(Button({tag:"div",class:"btn-toolbar" ,role:"toolbar"}));
		var loop = function(array) {
			btnGroup = Button({}, "group");
			toolbar.append(btnGroup);
			$.each(array, function(i, n) {
				if ($.isArray(n)) {
					//toolbar.append(Button({}))
					loop(n);
				} else {
					btnGroup.append($(plugins[n].init.call(edit, edit)));
				}
			});
		}
		loop(options.toolbar);
	}

	function bindCallback(el,context) {
		$(el).find("[data-event]").each(function(i, n) {
			$(n).on("click", function() {
				var eventValue = $(n).attr("data-value")
				$(n).attr("data-event").call(context, eventValue);
			});
		});
	}

	$.fn.extend({
		/**
		 * 构建编辑器
		 * @param  {Object} 编辑器初始化参数
		 * @return {Object} 包含编辑器方法的jQuery对象
		 */
		xyzEditor: function(opts) {
			var that = this;
			if (that.get(0).tagName !== "TEXTAREA") {
				error("需要textarea")
			}
			if (that.attr("data-source-code")) {
				error("不能重复定义textarea");
			}
			that.attr("data-source-code", "html");
			options = $.extend({}, options, opts);

			initBone(that);
			createToolbar(that);
			that.extend(coreEditor);
			return that;
		}
	});
	$.extend({
		xyzEditor: function(el, opts) {
			return $(el).xyzEditor(opts);
		},
		addPlugin: function(plugin) {
			plugins[plugin.name] = {
				init: function(coreEditor) {
					//工具栏上的按钮
					var btn = new Button(plugin.button);
					bindCallback(btn,plugin);

				}
			};
		}
	}),
})